<template>
  <div class="course-detail-container">
    <!-- 页面头部 - 标题居中与返回按钮在同一行 -->
    <div class="page-header">
      <div class="header-content">
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/trainingManagement/details' }">开课管理</el-breadcrumb-item>
          <el-breadcrumb-item>课程详细信息</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="title-container">
          <h1 class="title">课程详细信息</h1>
          <el-button @click="handleBack" class="back-btn">返回</el-button>
        </div>
      </div>
    </div>

    <!-- 课程基本信息 - 仅学期回显为"2025学年第一学期" -->
    <el-card class="course-form-card">
      <div slot="header">
        <span>课程基本信息</span>
      </div>
      <div class="info-grid">
        <div class="info-row">
          <div class="info-item">
            <span class="info-label">课程名称：</span>
            <span class="info-value">{{ courseInfo.courseName || '暂无数据' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">开课学院：</span>
            <span class="info-value">{{ courseInfo.department || '暂无数据' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">班级名称：</span>
            <span class="info-value">{{ courseInfo.className || '暂无数据' }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="info-label">开课学期：</span>
            <span class="info-value">{{ courseInfo.semester || '暂无数据' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">学年：</span>
            <span class="info-value">{{ courseInfo.academicYear === 0 ? 0 : (courseInfo.academicYear || '暂无数据') }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">班级最大容量：</span>
            <span class="info-value">{{ rowData.maxCapacity || '暂无数据' }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="info-label">已选学生人数：</span>
            <span class="info-value">{{ rowData.currentEnrollment || '暂无数据' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">是否满员：</span>
            <span class="info-value">{{ rowData.isFull === 1 ? '是' : '否' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">排课优先级：</span>
            <span class="info-value">{{ rowData.schedulePriority || '暂无数据' }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="info-label">是否排课完成：</span>
            <span class="info-value">{{ rowData.isScheduleCompleted === 1 ? '是' : '否' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">创建时间：</span>
            <span class="info-value">{{ rowData.createdAt || '暂无数据' }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 授课教师信息和授课教室信息 - 左右关系占满一行 -->
    <el-row :gutter="20" class="full-width-row">
      <el-col :span="12">
        <el-card class="info-card">
          <div slot="header">
            <span>授课教师信息</span>
          </div>
          <div class="card-content">
            <div class="teacher-info">
              <p>当前授课教师：
                <template v-if="currentTeacherNames.length > 0">
                  <span v-for="(name, index) in currentTeacherNames" :key="index">
                    {{ name }}
                    <template v-if="index < currentTeacherNames.length - 1">、</template>
                  </span>
                </template>
                <template v-else>未指定</template>
              </p>
              <!-- 禁用：选择授课教师按钮 -->
              <el-button
                  type="primary"
                  size="small"
                  @click="openSpecifiedTeacher = true"
                  style="margin-top: 10px; margin-left: auto; margin-right: auto; display: block;"
                  :disabled="isScheduleCompleted === 1"
              >
                选择授课教师
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="info-card">
          <div slot="header">
            <span>授课教室信息</span>
          </div>
          <div class="card-content">
            <!-- 禁用：教室选择下拉框 -->
            <el-select
                v-model="selectedClassroomIds"
                placeholder="请选择教室"
                @change="handleClassroomChange"
                style="width: 100%;"
                multiple
                collapse-tags
                filterable
                :disabled="isScheduleCompleted === 1"
            >
              <el-option
                  v-for="item in classrooms"
                  :key="item.id"
                  :label="`${item.classRoomName}`"
                  :value="item.id"
              />
            </el-select>
            <p style="margin-top: 10px;">当前选择教室：
              <template v-if="selectedClassroomIds.length > 0">
                <span v-for="(id, index) in selectedClassroomIds" :key="index">
                  {{ getClassroomNameById(id) }}
                  <template v-if="index < selectedClassroomIds.length - 1">、</template>
                </span>
              </template>
              <template v-else>未指定</template>
            </p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 核心布局调整：左侧垂直放置「授课时间设置」+「课程时间安排」，右侧放置「课表」 -->
    <el-row :gutter="20" class="full-width-row">
      <!-- 左侧列：占8格，垂直排列两个模块 -->
      <el-col :span="8">
        <!-- 授课时间设置（上） -->
        <el-card class="info-card mb-20">
          <div slot="header">
            <span>授课时间设置</span>
          </div>
          <div class="card-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <!-- 禁用：起始周下拉框 -->
                <el-select v-model="startWeek" placeholder="起始周" style="width: 100%;" :disabled="isScheduleCompleted === 1">
                  <el-option
                      v-for="dict in class_week"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="12">
                <!-- 禁用：结束周下拉框 -->
                <el-select v-model="endWeek" placeholder="结束周" style="width: 100%;" :disabled="isScheduleCompleted === 1">
                  <el-option
                      v-for="dict in class_week"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  />
                </el-select>
              </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 15px;">
              <el-col :span="12">
                <el-form-item label="每周授课次数：" label-width="150px" style="margin-bottom: 0;">
                  <!-- 禁用：每周授课次数输入框 -->
                  <el-input
                      v-model.number="weeklyClassCount"
                      placeholder="如：2"
                      type="number"
                      min="1"
                      max="7"
                      style="width: 100%;"
                      :disabled="isScheduleCompleted === 1"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="每次授课节数：" label-width="150px" style="margin-bottom: 0;">
                  <!-- 禁用：每次授课节数输入框 -->
                  <el-input
                      v-model.number="lessonsPerClass"
                      placeholder="如：3"
                      type="number"
                      min="1"
                      max="6"
                      style="width: 100%;"
                      :disabled="isScheduleCompleted === 1"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 禁用：保存课程设置按钮 -->
            <el-button
                type="primary"
                size="small"
                @click="saveCourseSettings"
                style="margin-top: 15px; margin-left: auto; margin-right: auto; display: block;"
                :disabled="isScheduleCompleted === 1"
            >
              保存课程设置
            </el-button>
          </div>
        </el-card>

        <!-- 课程时间安排（下）- 放在授课时间设置正下方 -->
        <el-card class="info-card" v-if="showTimeSchedule || weeklyClassCount > 0">
          <div slot="header">
            <span>课程时间安排</span>
          </div>
          <div class="card-content schedule-content">
            <div v-for="(slot, index) in timeSlots" :key="index" class="time-slot-group">
              <el-divider content="第{{ index + 1 }}次课" />
              <el-row :gutter="20" style="margin-top: 10px;">
                <el-col :span="12">
                  <el-form-item label="星期：" label-width="80px">
                    <!-- 禁用：星期下拉框 -->
                    <el-select v-model="slot.weekday" placeholder="选择星期" :disabled="isScheduleCompleted === 1">
                      <el-option label="周一" value="1"></el-option>
                      <el-option label="周二" value="2"></el-option>
                      <el-option label="周三" value="3"></el-option>
                      <el-option label="周四" value="4"></el-option>
                      <el-option label="周五" value="5"></el-option>
                      <el-option label="周六" value="6"></el-option>
                      <el-option label="周日" value="7"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="连续方式：" label-width="100px">
                    <!-- 禁用：连续方式下拉框 -->
                    <el-select v-model="slot.continuousMode" placeholder="选择连续方式" :disabled="isScheduleCompleted === 1">
                      <el-option
                          v-for="mode in continuous_class_mode"
                          :key="mode.value"
                          :label="mode.label"
                          :value="mode.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第二行：开始节次 + 结束节次 -->
              <el-row :gutter="20" style="margin-top: 10px;">
                <el-col :span="12">
                  <el-form-item label="开始节次：" label-width="100px">
                    <!-- 禁用：开始节次下拉框 -->
                    <el-select v-model="slot.startLesson" placeholder="选择开始节次" :disabled="isScheduleCompleted === 1">
                      <el-option v-for="i in 10" :key="i" :label="`第${i}节`" :value="i"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束节次：" label-width="100px">
                    <!-- 禁用：结束节次下拉框 -->
                    <el-select v-model="slot.endLesson" placeholder="选择结束节次" :disabled="isScheduleCompleted === 1">
                      <el-option v-for="i in 10" :key="i" :label="`第${i}节`" :value="i"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 禁用：保存时间安排按钮 -->
            <el-button
                type="success"
                style="margin-top: 20px; margin-left: auto; margin-right: auto; display: block;"
                @click="processAllTimeSlots"
                :disabled="timeSlots.length === 0 || isScheduleCompleted === 1"
            >
              保存时间安排
            </el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧列：占16格，放置课表（宽度更大，符合课表展示需求） -->
      <el-col :span="16">
        <el-card class="schedule-card">
          <div slot="header" style="text-align: center;">
            <span>课表</span>
          </div>
          <div class="card-content">
            <!-- 课表实现 -->
            <div class="grid-timetable">
              <!-- 顶部星期标题 -->
              <div class="timetable-header">
                <div class="header-cell empty-cell"></div>
                <div class="header-cell">星期一</div>
                <div class="header-cell">星期二</div>
                <div class="header-cell">星期三</div>
                <div class="header-cell">星期四</div>
                <div class="header-cell">星期五</div>
                <div class="header-cell">星期六</div>
                <div class="header-cell">星期日</div>
              </div>

              <!-- 课表主体（网格布局） -->
              <div class="timetable-body">
                <!-- 左侧节次列 -->
                <div class="lesson-index-column">
                  <div v-for="i in 10" :key="i" class="lesson-index">
                    <div class="lesson-time">
                      {{ getTimeRange(i) }}
                    </div>
                    <div class="lesson-number">
                      第{{ i }}节
                    </div>
                  </div>
                </div>

                <!-- 网格内容区域 -->
                <div class="timetable-grid">
                  <div class="grid-container">
                    <!-- 动态生成课程元素 -->
                    <div
                        v-for="(course, index) in allCourses"
                        :key="index"
                        class="course-item"
                        :style="getCourseStyle(course)"
                        :class="`course-type-${course.type}`"
                    >
                      <div class="course-title">{{ course.title }}</div>
                      <div class="course-detail">{{ course.skjc }}</div>
                      <div class="course-detail">{{ course.addr }}</div>
                      <div class="course-detail">{{ course.jxbzc }}</div>
                      <div class="course-detail">{{ course.num }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 禁用：提交更新课程信息按钮 -->
            <el-button
                type="success"
                style="margin-top: 20px; width: 100%;"
                @click="submitAllCourseInfo"
                :loading="submitLoading"
                :disabled="isScheduleCompleted === 1"
            >
              提交更新课程信息
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 教师选择对话框 -->
    <el-dialog v-model="openSpecifiedTeacher" title="选择授课教师" width="500px">
      <el-form>
        <el-form-item label="授课教师" prop="secretaryTeacherId">
          <!-- 禁用：教师选择下拉框 -->
          <el-select
              v-model="form.secretaryTeacherId"
              placeholder="请输入教师姓名"
              clearable
              filterable
              remote
              :remote-method="filterTeachers"
              style="width: 100%;"
              :loading="teacherLoading"
              multiple
              collapse-tags
              :disabled="isScheduleCompleted === 1"
          >
            <el-option
                v-for="teacher in filteredTeachers"
                :key="teacher.uuid"
                :label="`${teacher.name} (${teacher.teacherCode})`"
                :value="teacher.uuid"
            >
              <span style="float: left">{{ teacher.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ teacher.teacherCode }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- 禁用：对话框确定按钮 -->
          <el-button type="primary" @click="submitAssignTeacher" :disabled="isScheduleCompleted === 1">确 定</el-button>
          <el-button @click="openSpecifiedTeacher = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, watch, reactive, getCurrentInstance, nextTick} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage, ElLoading} from 'element-plus';
import {debounce} from 'lodash-es';
import {listClassroom} from "@/api/classroom/classroom";

const {proxy} = getCurrentInstance();
import {listTeacher} from "@/api/teacher/teacher";
import {selectTeacherListByCollegeIds} from "@/api/student/allList";
import {listsClassroom} from "@/api/classroom/classroom";
import {assignTeacher} from "@/api/trainingManagement/details";
import {
  getResourceTimetable,
  getStudentTimetable,
  submitCourseInfo,
  getAllByCourseScheduleDetailsId
} from "@/api/course/availability";
// 引入连续方式字典
const {continuous_class_mode, class_week} = proxy.useDict('continuous_class_mode', 'class_week');
// 存储所有需要显示的课程（合并所有类型）
const allCourses = ref([]);
// 存储接口返回的完整排课数据（供回显使用）
const scheduleApiData = ref({});

// 核心新增：排课完成状态（0=未完成，1=已完成）
const isScheduleCompleted = ref(0);

// 原有数据变量保持不变
const teacherUsedTime = ref([]);
const startWeek = ref('');
const endWeek = ref('');
const weeklyClassCount = ref(1);
const lessonsPerClass = ref(2);
const showTimeSchedule = ref(false);
const timeSlots = ref([]);
const studentTimetableData = ref([]);
const submitLoading = ref(false);
const route = useRoute();
const router = useRouter();
const rowData = ref({});
const classrooms = ref([]);
const selectedClassroomIds = ref([]);  // 教室多选数组
const currentClassroomName = ref('');
const classroomUsedTime = ref([]);
const courseInfo = ref({
  courseId: '',
  courseName: '',
  className: '',
  semester: '',          // 仅回显"2025学年第一学期"
  semesterId: '',
  department: '',
  academicYear: ''
});

// 教师相关变量 - 数组格式（适配后端List<String>）
const openSpecifiedTeacher = ref(false);
const teacherList = ref([]);
const filteredTeachers = ref([]);
const form = reactive({
  secretaryTeacherId: []  // 教师多选数组
});
const teacherLoading = ref(false);
const currentTeacherIds = ref([]);  // 提交给后端的教师ID数组
const currentTeacherNames = ref([]);  // 显示用的教师名称数组

// 新方法：获取课程样式（网格定位）
const getCourseStyle = (course) => {
  const colIndex = course.xq - 1;
  const rowIndex = course.start - 1;
  const rowSpan = course.end - course.start + 1;
  return {
    gridColumn: `${colIndex + 1} / span 1`,
    gridRow: `${rowIndex + 1} / span ${rowSpan}`,
    zIndex: course.type
  };
};

// 初始化时间安排表单
const initTimeSlots = () => {
  timeSlots.value = [];
  const count = Math.min(Math.max(Number(weeklyClassCount.value) || 1, 1), 7);
  for (let i = 0; i < count; i++) {
    timeSlots.value.push({
      weekday: "",
      startLesson: "",
      endLesson: "",
      continuousMode: ""
    });
  }
};

// 辅助方法：获取节次对应的时间范围
const getTimeRange = (lessonNum) => {
  const timeRanges = [
    '10:00-10:45', '10:55-11:40', '12:10-12:55', '13:05-13:50',
    '15:00-15:45', '15:55-16:40', '17:10-17:55', '18:05-18:50',
    '21:00-21:45', '21:55-22:40'
  ];
  return timeRanges[lessonNum - 1] || '';
};

// 合并所有课程数据（含接口已排课数据）
const mergeAllCourses = () => {
  allCourses.value = [];
  const {classScheduleDetailedList, courseScheduleDetails} = scheduleApiData.value;
  const classroomName = getClassroomNameById(courseScheduleDetails?.classroom) || '未知教室';
  const courseName = courseInfo.value.courseName || '未知课程';
  const weekRange = `${courseScheduleDetails?.startWeek || ''}-${courseScheduleDetails?.endWeek || ''}周`;

  // 1. 接口返回的已排课数据（type:5，差异化样式）
  if (Array.isArray(classScheduleDetailedList) && classScheduleDetailedList.length > 0) {
    classScheduleDetailedList.forEach(item => {
      const start = parseInt(item.startTime?.replace(/第|节/g, '') || '0');
      const end = parseInt(item.endTime?.replace(/第|节/g, '') || '0');
      const weekDay = item.weekDay || 0;
      const weekType = item.weekType === 1 ? '连续周' : item.weekType === 2 ? '单周' : '双周';

      if (!isNaN(start) && !isNaN(end) && start >= 1 && end <= 10 && weekDay >= 1) {
        allCourses.value.push({
          type: 5,
          xq: weekDay,
          start: start,
          end: end,
          title: `${courseName}（已排）`,
          addr: classroomName,
          skjc: `${start}-${end}节`,
          jxbzc: weekType,
          num: weekRange
        });
      }
    });
  }

  // 2. 原有其他类型数据（保持不变）
  const courseEvents = rowData.value.courseSchedule || [];
  courseEvents.forEach(event => {
    allCourses.value.push({...event, type: 1});
  });
  studentTimetableData.value.forEach(course => {
    allCourses.value.push({...course, type: 2});
  });
  teacherUsedTime.value.forEach(course => {
    allCourses.value.push({...course, type: 3});
  });
  classroomUsedTime.value.forEach(course => {
    allCourses.value.push({...course, type: 4});
  });

  // 排序（按星期→开始节次）
  allCourses.value.sort((a, b) => {
    if (a.xq !== b.xq) return a.xq - b.xq;
    return a.start - b.start;
  });
};

// 原有方法保持不变：教室已用时间转换
const transformClassroomTime = (weekdays) => {
  classroomUsedTime.value = [];
  weekdays.forEach(weekday => {
    const xq = weekday.dayOfWeek;
    weekday.timeSlots.forEach(slot => {
      slot.courses.forEach(course => {
        const start = parseInt(course.startLesson);
        const end = parseInt(course.endLesson);
        if (!isNaN(start) && !isNaN(end) && start >= 1 && end <= 10) {
          classroomUsedTime.value.push({
            xq: xq,
            start: start,
            end: end,
            title: course.title || "教室已用",
            addr: course.location || "",
            skjc: `${start}-${end}节`
          });
        }
      });
    });
  });
  mergeAllCourses();
};

// 原有方法保持不变：教师已用时间转换
const transformTeacherTime = (weekdays) => {
  teacherUsedTime.value = [];
  weekdays.forEach(weekday => {
    const xq = weekday.dayOfWeek;
    weekday.timeSlots.forEach(slot => {
      slot.courses.forEach(course => {
        const start = parseInt(course.startLesson);
        const end = parseInt(course.endLesson);
        if (!isNaN(start) && !isNaN(end) && start >= 1 && end <= 10) {
          teacherUsedTime.value.push({
            xq: xq,
            start: start,
            end: end,
            title: course.title || "教师已用",
            addr: course.location || "",
            skjc: `${start}-${end}节`
          });
        }
      });
    });
  });
  mergeAllCourses();
};

// 原有方法保持不变：学生课程转换
const transformStudentTimetable = (weekdays) => {
  studentTimetableData.value = [];
  weekdays.forEach(weekday => {
    const xq = weekday.dayOfWeek;
    weekday.timeSlots.forEach(slot => {
      slot.courses.forEach(course => {
        const start = parseInt(course.startLesson);
        const end = parseInt(course.endLesson);
        if (!isNaN(start) && !isNaN(end) && start >= 1 && end <= 10) {
          studentTimetableData.value.push({
            xq: xq,
            start: start,
            end: end,
            title: course.title || "学生课程",
            addr: course.location || "",
            skjc: `${start}-${end}节`,
            jxbzc: course.extraInfo?.weekType || '',
            num: course.extraInfo?.lessonCount || ''
          });
        }
      });
    });
  });
  mergeAllCourses();
};

// 原有方法保持不变：提交课程信息
const submitAllCourseInfo = async () => {
  if (!validateSubmitData()) {
    return;
  }

  submitLoading.value = true;
  try {
    rowData.value.lesson_count = Number(lessonsPerClass.value);
    rowData.value.week_type = Number(weeklyClassCount.value);
    rowData.value.course_period = timeSlots.value
        .map(slot => slot.continuousMode || '')
        .join('');

    const classroomIdsStr = selectedClassroomIds.value.join(',');
    const submitData = {
      courseId: rowData.value.id,
      maxCapacity: rowData.value.maxCapacity,
      currentEnrollment: rowData.value.currentEnrollment,
      teacherId: currentTeacherIds.value,
      classroomId: classroomIdsStr,
      startWeek: Number(startWeek.value),
      endWeek: Number(endWeek.value),
      weeklyClassCount: Number(weeklyClassCount.value),
      lessonsPerClass: Number(lessonsPerClass.value),
      academicYear: courseInfo.value.academicYear,
      semesterId: courseInfo.semesterId,
      coursePeriod: rowData.value.course_period,
      courseSchedule: (rowData.value.courseSchedule || []).map(item => ({
        xq: Number(item.xq),
        start: Number(item.start),
        end: Number(item.end),
        reason: item.title || courseInfo.value.courseName
      })),
      courseScheduleDetails: [rowData.value]
    };

    const response = await submitCourseInfo(submitData);
    if (response.code === 200) {
      ElMessage.success("课程信息提交成功");
    } else {
      ElMessage.error(response.message || "提交失败，请重试");
    }
  } catch (error) {
    console.error("提交课程信息失败:", error);
    ElMessage.error("网络错误，提交失败");
  } finally {
    submitLoading.value = false;
  }
};

// 原有方法保持不变：保存课程设置
const saveCourseSettings = async () => {
  if (!startWeek.value || !endWeek.value) {
    ElMessage.warning("请选择起始周和结束周");
    return;
  }
  if (startWeek.value > endWeek.value) {
    ElMessage.warning("起始周不能大于结束周");
    return;
  }
  if (!weeklyClassCount.value || weeklyClassCount.value < 1 || weeklyClassCount.value > 7) {
    ElMessage.warning("一周上课次数必须在1-7之间");
    return;
  }
  if (!lessonsPerClass.value || lessonsPerClass.value < 1 || lessonsPerClass.value > 6) {
    ElMessage.warning("一次上课节数必须在1-6之间");
    return;
  }

  try {
    rowData.value.week_type = Number(weeklyClassCount.value);
    rowData.value.lesson_count = Number(lessonsPerClass.value);
    rowData.value.startWeek = Number(startWeek.value);
    rowData.value.endWeek = Number(endWeek.value);
    rowData.value.weeklyClassCount = Number(weeklyClassCount.value);
    rowData.value.lessonCount = Number(lessonsPerClass.value);

    ElMessage.success("课程设置保存成功");
    const count = Number(weeklyClassCount.value);
    weeklyClassCount.value = count;
    await nextTick();
    initTimeSlots();
    showTimeSchedule.value = true;
  } catch (error) {
    console.error("保存课程设置失败：", error);
    ElMessage.error("网络错误，保存失败");
  }
};

// 原有方法保持不变：提交验证
const validateSubmitData = () => {
  if (currentTeacherIds.value.length === 0) {
    ElMessage.warning("请选择至少一名授课教师");
    return false;
  }
  if (selectedClassroomIds.value.length === 0) {
    ElMessage.warning("请选择至少一个授课教室");
    return false;
  }
  if (!startWeek.value || !endWeek.value || startWeek.value > endWeek.value) {
    ElMessage.warning("请正确设置起始周和结束周");
    return false;
  }
  if (!weeklyClassCount.value || weeklyClassCount.value < 1 || weeklyClassCount.value > 7) {
    ElMessage.warning("每周授课次数必须在1-7之间");
    return false;
  }
  if (!lessonsPerClass.value || lessonsPerClass.value < 1 || lessonsPerClass.value > 6) {
    ElMessage.warning("一次上课节数必须在1-6之间");
    return false;
  }
  if (!rowData.value.courseSchedule || rowData.value.courseSchedule.length !== weeklyClassCount.value) {
    ElMessage.warning("请完成所有课时的时间安排");
    return false;
  }
  for (let i = 0; i < timeSlots.value.length; i++) {
    if (!timeSlots.value[i].continuousMode) {
      ElMessage.warning(`第${i + 1}次课请选择连续方式`);
      return false;
    }
  }
  for (let i = 0; i < rowData.value.courseSchedule.length; i++) {
    const schedule = rowData.value.courseSchedule[i];
    if (!schedule || !schedule.xq || !schedule.start || !schedule.end) {
      ElMessage.warning(`第${i + 1}次课的时间安排不完整`);
      return false;
    }
  }
  const coursePeriod = timeSlots.value.map(slot => slot.continuousMode).join('');
  if (!coursePeriod || !/^\d+$/.test(coursePeriod)) {
    ElMessage.warning("连续方式必须为纯数字，不可包含其他字符");
    return false;
  }
  return true;
};

// 原有方法保持不变：获取教室列表
const getClassroomList = async () => {
  try {
    const res = await listsClassroom({});
    if (Array.isArray(res)) {
      classrooms.value = res;
    } else if (res && Array.isArray(res.rows)) {
      classrooms.value = res.rows;
    } else if (res && res.code === 200 && Array.isArray(res.data)) {
      classrooms.value = res.data;
    } else {
      console.error('无法解析的教室数据格式:', res);
      classrooms.value = [];
      ElMessage.warning("教室数据格式异常");
      return;
    }

    // 初始化教室ID（兼容旧数据）
    if (rowData.value.classroomId && classrooms.value.length > 0) {
      selectedClassroomIds.value = typeof rowData.value.classroomId === 'string'
          ? rowData.value.classroomId.split(',')
          : rowData.value.classroomId;

      const validIds = selectedClassroomIds.value.filter(id =>
          classrooms.value.some(classroom => classroom.id === id)
      );
      if (validIds.length !== selectedClassroomIds.value.length) {
        console.warn("部分初始教室ID不存在，已过滤");
        selectedClassroomIds.value = validIds;
      }
    }

    if (classrooms.value.length === 0) {
      ElMessage.warning("暂无可用教室");
    } else {
      ElMessage.success(`加载了 ${classrooms.value.length} 个教室`);
    }
  } catch (err) {
    console.error('教室数据加载失败:', err);
    ElMessage.error("教室列表加载失败");
  }
};

// 原有方法保持不变：根据ID获取教室名称
const getClassroomNameById = (id) => {
  const classroom = classrooms.value.find(c => c.id === id);
  return classroom ? `${classroom.classRoomName}` : '未知教室';
};

// 原有方法保持不变：获取教室已用时间
const fetchClassroomUsedTime = (classroomId) => {
  const academicYear = courseInfo.value.academicYear;
  if (academicYear === undefined) {
    ElMessage.warning("未获取到学年信息，无法加载教室时间");
    return;
  }

  getResourceTimetable(classroomId, academicYear)
      .then(response => {
        const classroomData = response.params?.data;
        if (response.code === 200 && classroomData?.weekdays) {
          transformClassroomTime(classroomData.weekdays);
        } else {
          ElMessage.warning("未获取到教室时间数据");
        }
      })
      .catch(error => {
        console.error("获取教室时间失败:", error);
      });
};

// 原有方法保持不变：教室选择变更
const handleClassroomChange = (classroomIds) => {
  if (!classroomIds || classroomIds.length === 0) {
    classroomUsedTime.value = [];
    mergeAllCourses();
    return;
  }
  fetchClassroomUsedTime(classroomIds[0]);
};

// 原有方法保持不变：获取教师列表
const getTeacherList = async () => {
  try {
    if (teacherList.value.length === 0) {
      const res = await selectTeacherListByCollegeIds({});
      teacherList.value = res.rows;
      filteredTeachers.value = res.rows;
      updateCurrentTeacherNames();
    }
  } catch (err) {
    console.error('教师数据加载失败:', err);
    ElMessage.error("教师列表加载失败");
  }
};

// 原有方法保持不变：教师筛选
const filterTeachers = debounce(async (query) => {
  teacherLoading.value = true;
  try {
    if (query) {
      const lowerQuery = query.trim().toLowerCase();
      filteredTeachers.value = teacherList.value.filter(teacher =>
          teacher.name?.toLowerCase().includes(lowerQuery) ||
          teacher.teacherCode?.includes(query)
      );
    } else {
      filteredTeachers.value = teacherList.value;
    }
  } finally {
    teacherLoading.value = false;
  }
}, 300);

// 原有方法保持不变：更新教师名称
const updateCurrentTeacherNames = () => {
  currentTeacherNames.value = [];
  if (currentTeacherIds.value.length > 0) {
    currentTeacherIds.value.forEach(teacherId => {
      const teacher = teacherList.value.find(t => t.uuid === teacherId);
      if (teacher) {
        currentTeacherNames.value.push(`${teacher.name} (${teacher.teacherCode})`);
      }
    });
  }
};

// 原有方法保持不变：提交教师选择
const submitAssignTeacher = () => {
  if (!form.secretaryTeacherId || form.secretaryTeacherId.length === 0) {
    ElMessage.warning("请至少选择一名授课教师");
    return;
  }

  currentTeacherIds.value = [...form.secretaryTeacherId];
  updateCurrentTeacherNames();
  if (currentTeacherIds.value.length > 0) {
    fetchTeacherUsedTime(currentTeacherIds.value[0]);
  }
  openSpecifiedTeacher.value = false;
  ElMessage.success("教师选择成功");
};

// 原有方法保持不变：获取教师已用时间
const fetchTeacherUsedTime = (teacherId) => {
  const academicYear = courseInfo.value.academicYear;
  if (academicYear === undefined) {
    ElMessage.warning("未获取到学年信息，无法加载教师时间");
    return;
  }

  getResourceTimetable(teacherId, academicYear)
      .then(response => {
        const teacherData = response.params?.data;
        if (response.code === 200 && teacherData?.weekdays) {
          transformTeacherTime(teacherData.weekdays);
        } else {
          ElMessage.warning("未获取到教师时间数据");
        }
      })
      .catch(error => {
        console.error("获取教师时间失败:", error);
      });
};

// 原有方法保持不变：获取学生课表
const fetchStudentTimetable = async () => {
  const courseScheduleDetailsId = rowData.value.id;
  if (!courseScheduleDetailsId) {
    ElMessage.warning("未获取到课程安排详情ID，无法加载学生课表");
    return;
  }

  const loading = ElLoading.service({
    lock: true,
    text: "正在加载学生课表数据...",
    target: ".side-card .card-content"
  });

  try {
    const response = await getStudentTimetable(courseScheduleDetailsId);
    if (response.code !== 200) {
      throw new Error(response.message || '获取失败');
    }

    const responseData = response.params?.data;
    if (!responseData) {
      throw new Error("数据格式错误");
    }

    if (responseData.weekdays && Array.isArray(responseData.weekdays)) {
      transformStudentTimetable(responseData.weekdays);
      const lessonCount = responseData.weekdays.reduce((total, weekday) =>
          total + (weekday.timeSlots?.reduce((slotTotal, slot) =>
              slotTotal + (slot.courses?.length || 0), 0) || 0), 0);
      ElMessage.success(`加载学生课表数据，共${lessonCount}节课`);
    } else {
      ElMessage.info("当前课程暂无学生课表数据");
    }
  } catch (error) {
    console.error("获取学生课表失败:", error);
    ElMessage.error(`加载学生课表失败: ${error.message}`);
  } finally {
    loading.close();
  }
};

// 原有方法保持不变：检测时间冲突
const checkTimeConflict = (newEvent) => {
  if (rowData.value.courseSchedule && rowData.value.courseSchedule.length) {
    for (const course of rowData.value.courseSchedule) {
      if (course.xq === newEvent.xq) {
        if (
            (newEvent.start >= course.start && newEvent.start <= course.end) ||
            (newEvent.end >= course.start && newEvent.end <= course.end) ||
            (newEvent.start <= course.start && newEvent.end >= course.end)
        ) {
          return {hasConflict: true, message: `与已安排的第${course.start}-${course.end}节课冲突`};
        }
      }
    }
  }
  for (const teacherCourse of teacherUsedTime.value) {
    if (teacherCourse.xq === newEvent.xq) {
      if (
          (newEvent.start >= teacherCourse.start && newEvent.start <= teacherCourse.end) ||
          (newEvent.end >= teacherCourse.start && newEvent.end <= teacherCourse.end) ||
          (newEvent.start <= teacherCourse.start && newEvent.end >= teacherCourse.end)
      ) {
        return {hasConflict: true, message: `与教师已安排的第${teacherCourse.start}-${teacherCourse.end}节课冲突`};
      }
    }
  }
  for (const roomCourse of classroomUsedTime.value) {
    if (roomCourse.xq === newEvent.xq) {
      if (
          (newEvent.start >= roomCourse.start && newEvent.start <= roomCourse.end) ||
          (newEvent.end >= roomCourse.start && newEvent.end <= roomCourse.end) ||
          (newEvent.start <= roomCourse.start && newEvent.end >= roomCourse.end)
      ) {
        return {hasConflict: true, message: `与教室已安排的第${roomCourse.start}-${roomCourse.end}节课冲突`};
      }
    }
  }
  for (const studentCourse of studentTimetableData.value) {
    if (studentCourse.xq === newEvent.xq) {
      if (
          (newEvent.start >= studentCourse.start && newEvent.start <= studentCourse.end) ||
          (newEvent.end >= studentCourse.start && newEvent.end <= studentCourse.end) ||
          (newEvent.start <= studentCourse.start && newEvent.end >= studentCourse.end)
      ) {
        return {hasConflict: true, message: `与学生已选的第${studentCourse.start}-${studentCourse.end}节课冲突`};
      }
    }
  }
  return {hasConflict: false};
};

// 原有方法保持不变：保存单条时间安排
const saveTimeSchedule = (index) => {
  const slot = timeSlots.value[index];
  if (!slot) return Promise.reject(new Error(`第${index + 1}次课数据不存在`));
  if (!slot.weekday || !slot.startLesson || !slot.endLesson) return Promise.reject(new Error(`第${index + 1}次课信息不完整`));

  const xq = parseInt(slot.weekday, 10);
  const start = parseInt(slot.startLesson, 10);
  const end = parseInt(slot.endLesson, 10);

  if (isNaN(xq) || isNaN(start) || isNaN(end)) return Promise.reject(new Error(`第${index + 1}次课数据格式错误`));
  if (xq < 1 || xq > 7) return Promise.reject(new Error(`第${index + 1}次课星期值无效`));
  if (start >= end || start < 1 || end > 10) return Promise.reject(new Error(`第${index + 1}次课节次无效`));

  const newEvent = {
    xq: xq,
    start: start,
    end: end,
    title: `${courseInfo.value.courseName}（第${index + 1}次）`,
    addr: selectedClassroomIds.value.map(id => getClassroomNameById(id)).join(','),
    skjc: `${start}-${end}节`,
    jxbzc: courseInfo.value.className || '',
    num: `第${startWeek.value}-${endWeek.value}周`
  };

  const conflictCheck = checkTimeConflict(newEvent);
  if (conflictCheck.hasConflict) return Promise.reject(new Error(`第${index + 1}次课${conflictCheck.message}，请重新选择时间`));

  if (!rowData.value.courseSchedule) rowData.value.courseSchedule = [];
  const updatedSchedule = [...rowData.value.courseSchedule];
  updatedSchedule[index] = newEvent;
  rowData.value.courseSchedule = updatedSchedule;

  mergeAllCourses();
  return nextTick().then(() => true);
};

// 原有方法保持不变：批量保存时间安排
const processAllTimeSlots = async () => {
  rowData.value.courseSchedule = [];
  mergeAllCourses();
  await nextTick();

  let hasError = false;
  for (let i = 0; i < timeSlots.value.length; i++) {
    try {
      await saveTimeSchedule(i);
      ElMessage.success(`第${i + 1}次课时间安排已保存`);
      await new Promise(resolve => setTimeout(resolve, 50));
    } catch (error) {
      hasError = true;
      ElMessage.error(error.message);
    }
  }

  if (!hasError) {
    ElMessage.success(`所有${timeSlots.value.length}次课时间安排已处理`);
  } else {
    ElMessage.warning('部分课程时间安排存在冲突，请检查并修正');
  }
};

// 原有方法保持不变：返回按钮
const handleBack = () => {
  router.push('/trainingManagement/details');
};

// 核心修改：调用接口并回显数据（仅保留学期+教师+教室+时间设置+时间安排）
const fetchClassScheduleDetails = async () => {
  const courseScheduleDetailsId = rowData.value?.id;
  if (!courseScheduleDetailsId) {
    console.warn("未获取到课程班ID，无法调用排课详情接口");
    ElMessage.warning("未获取到课程班ID，无法加载排课详细信息");
    return;
  }

  try {
    console.log("调用getAllByCourseScheduleDetailsId接口，课程班ID：", courseScheduleDetailsId);
    // 调用接口（返回对象，非数组）
    const apiRes = await getAllByCourseScheduleDetailsId(courseScheduleDetailsId);
    scheduleApiData.value = apiRes;
    const {teacherIds, classScheduleDetailedList, courseScheduleDetails} = apiRes;

    if (!courseScheduleDetails) {
      ElMessage.warning("接口缺少课程基础数据");
      return;
    }

    // -------------------------- 1. 回显学期（仅这一行课程基本信息） --------------------------
    const semesterNum = courseScheduleDetails.semester;
    const grade = courseScheduleDetails.grade;
    if (semesterNum && grade) {
      const semesterMap = {1: '第一学期', 2: '第二学期'};
      courseInfo.value.semester = `${grade}学年${semesterMap[semesterNum] || '未知学期'}`;
      courseInfo.value.academicYear = grade; // 同步学年
    }

    // -------------------------- 2. 回显授课教师 --------------------------
    if (Array.isArray(teacherIds) && teacherIds.length > 0) {
      // 等待教师列表加载完成
      await new Promise(resolve => {
        const checkTeacherList = () => {
          if (teacherList.value.length > 0) resolve();
          else setTimeout(checkTeacherList, 100);
        };
        checkTeacherList();
      });

      currentTeacherIds.value = teacherIds;
      updateCurrentTeacherNames();
      form.secretaryTeacherId = [...teacherIds]; // 同步下拉框
      if (teacherIds[0]) fetchTeacherUsedTime(teacherIds[0]);
    }

    // -------------------------- 3. 回显授课教室 --------------------------
    const classroomId = courseScheduleDetails.classroom;
    if (classroomId && typeof classroomId === 'string') {
      // 等待教室列表加载完成
      await new Promise(resolve => {
        const checkClassroomList = () => {
          if (classrooms.value.length > 0) resolve();
          else setTimeout(checkClassroomList, 100);
        };
        checkClassroomList();
      });

      // 验证教室ID有效性
      const isValidClassroom = classrooms.value.some(c => c.id === classroomId);
      if (!isValidClassroom) {
        ElMessage.warning(`教室ID ${classroomId} 无效，无法回显`);
        return;
      }

      selectedClassroomIds.value = [classroomId];
      rowData.value.classroomId = classroomId; // 同步rowData
      handleClassroomChange(selectedClassroomIds.value);
    }

    // -------------------------- 4. 回显授课时间设置 --------------------------
    const apiStartWeek = courseScheduleDetails.startWeek;
    const apiEndWeek = courseScheduleDetails.endWeek;
    const apiLessonCount = courseScheduleDetails.lessonCount;
    const weeklyCount = Array.isArray(classScheduleDetailedList) ? classScheduleDetailedList.length : 1;

    // 赋值时间设置变量
    startWeek.value = apiStartWeek?.toString() || '';
    endWeek.value = apiEndWeek?.toString() || '';
    weeklyClassCount.value = weeklyCount;
    lessonsPerClass.value = apiLessonCount || 2;

    // 同步rowData（确保保存逻辑兼容）
    rowData.value.startWeek = apiStartWeek;
    rowData.value.endWeek = apiEndWeek;
    rowData.value.weeklyClassCount = weeklyCount;
    rowData.value.lessonsPerClass = apiLessonCount;

    // 触发保存逻辑，初始化时间安排数量
    await saveCourseSettings();

    // -------------------------- 5. 回显课程时间安排 --------------------------
    if (Array.isArray(classScheduleDetailedList) && classScheduleDetailedList.length > 0) {
      classScheduleDetailedList.forEach((item, index) => {
        const slot = timeSlots.value[index];
        if (!slot) return;

        // 解析星期（2→周二）
        slot.weekday = item.weekDay?.toString() || '';
        // 解析节次（“第1节”→1）
        const startLessonNum = item.startTime?.replace(/第|节/g, '') || '';
        const endLessonNum = item.endTime?.replace(/第|节/g, '') || '';
        slot.startLesson = startLessonNum;
        slot.endLesson = endLessonNum;
        // 解析连续方式（weekType:1→单周）
        slot.continuousMode = item.weekType?.toString() || '';
      });

      showTimeSchedule.value = true;
      mergeAllCourses(); // 触发课表渲染
    }

    ElMessage.success("所有排课数据回显完成！");
  } catch (error) {
    console.error("排课数据回显失败：", error);
    ElMessage.error("加载排课数据失败，请刷新页面重试");
  }
};

// 原有初始化逻辑：添加排课完成状态初始化
onMounted(() => {
  try {

    const rowDataStr = route.query.rowData;
    if (rowDataStr) {
      rowData.value = JSON.parse(rowDataStr);
      // 核心新增：初始化排课完成状态
      isScheduleCompleted.value = rowData.value.isScheduleCompleted || 0;

      // 初始化课程信息（基础数据，非接口回显）
      courseInfo.value = {
        courseId: rowData.value.courseId,
        courseName: rowData.value.courseName,
        className: rowData.value.className,
        semester: rowData.value.semester || '', // 初始值，接口回显会覆盖
        semesterId: rowData.value.semesterId,
        department: rowData.value.department,
        academicYear: rowData.value.academicYear
      };

      // 初始化教师ID（兼容旧数据，接口回显会覆盖）
      if (rowData.value.teacherId) {
        currentTeacherIds.value = typeof rowData.value.teacherId === 'string'
            ? rowData.value.teacherId.split(',')
            : rowData.value.teacherId;
      }

      // 加载基础列表 + 调用回显函数
      getTeacherList();
      getClassroomList();
      fetchStudentTimetable();
      initTimeSlots();
      fetchClassScheduleDetails(); // 关键：调用接口回显
    } else {
      ElMessage.warning("未获取到课程信息");
    }
  } catch (error) {
    console.error("数据解析失败：", error);
    ElMessage.error("数据解析失败，请返回重试");
  }
});

// 原有监听逻辑保持不变
watch(
    () => weeklyClassCount.value,
    (newCount) => {
      if (showTimeSchedule.value) {
        initTimeSlots();
      }
    }
);

watch(rowData, (newRowData) => {
  updateCurrentTeacherNames();
  // 同步学期和教师/教室ID
  courseInfo.value.academicYear = newRowData.academicYear;
  courseInfo.value.semesterId = newRowData.semesterId;

  if (newRowData.teacherId) {
    currentTeacherIds.value = typeof newRowData.teacherId === 'string'
        ? newRowData.teacherId.split(',')
        : newRowData.teacherId;
  }

  if (newRowData.classroomId) {
    selectedClassroomIds.value = typeof newRowData.classroomId === 'string'
        ? newRowData.classroomId.split(',')
        : newRowData.classroomId;
  }

  // 同步时间设置
  startWeek.value = newRowData.startWeek || '';
  endWeek.value = newRowData.endWeek || '';
  weeklyClassCount.value = newRowData.weeklyClassCount || 1;
  lessonsPerClass.value = newRowData.lessonsPerClass || 2;

  // 同步排课完成状态
  isScheduleCompleted.value = newRowData.isScheduleCompleted || 0;

  mergeAllCourses();
}, {deep: true});
</script>

<style scoped lang="scss">
// 容器样式 - 减少左右留白，让内容更宽
.course-detail-container {
  padding: 20px 15px;
  max-width: 100%;
  width: 100%;
  margin: 0 auto;
  box-sizing: border-box;
}

// 页面头部样式
.page-header {
  margin-bottom: 20px;

  .header-content {
    width: 100%;
  }

  .breadcrumb {
    margin-bottom: 15px;
  }

  .title-container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    height: 60px;
  }

  .title {
    margin: 0;
    font-size: 24px;
    font-weight: bold;
    color: #333;
  }

  .back-btn {
    position: absolute;
    left: 0;
  }
}

// 课程基本信息卡片样式
.course-form-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  .info-grid {
    padding: 15px 20px;
  }

  .info-row {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 8px;
    padding-bottom: 8px;
    border-bottom: 1px dashed #eee;

    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }
  }

  .info-item {
    flex: 1;
    min-width: 250px;
    padding: 5px 15px;
    box-sizing: border-box;

    .info-label {
      display: inline-block;
      width: 120px;
      font-weight: 500;
      color: #606266;
    }

    .info-value {
      color: #303133;
      line-height: 1.5;
    }
  }
}

// 占满一行的行容器
.full-width-row {
  width: 100%;
  margin-bottom: 20px;
}

// 信息卡片通用样式
.info-card {
  max-height: 450px;
  overflow-y: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  .card-content {
    padding: 15px;
  }
}

// 左侧两个卡片的间距
.mb-20 {
  margin-bottom: 20px;
}

// 时间安排内容样式
.schedule-content {
  max-height: 400px;
  overflow-y: auto;

  .time-slot-group {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px dashed #eee;

    &:last-child {
      margin-bottom: 0;
      padding-bottom: 0;
      border-bottom: none;
    }
  }
}

// 课表卡片样式
.schedule-card {
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  .card-content {
    padding: 15px;
    overflow-x: auto;
  }
}

// 教师信息样式
.teacher-info {
  padding: 5px 0;
}

// 课表样式 - 优化网格线显示
.grid-timetable {
  width: 100%;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 10px;
  min-width: 900px;
  background-color: #ffffff;
}

.timetable-header {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  background-color: #f5f7fa;
}

.header-cell {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  font-weight: bold;
  border-right: 1px solid #e8e8e8;

  &:last-child {
    border-right: none;
  }
}

.empty-cell {
  flex: 0 0 120px;
  border-right: 1px solid #e8e8e8;
}

.timetable-body {
  display: flex;
}

.lesson-index-column {
  width: 120px;
  border-right: 1px solid #e8e8e8;
  background-color: #f5f7fa;
}

.lesson-index {
  height: 80px;
  border-bottom: 1px solid #e8e8e8;
  padding: 5px;
  box-sizing: border-box;

  &:last-child {
    border-bottom: none;
  }
}

.lesson-time {
  font-size: 12px;
  color: #666;
}

.lesson-number {
  font-size: 14px;
  font-weight: bold;
  margin-top: 5px;
}

.timetable-grid {
  flex: 1;
}

// 优化网格线
.grid-container {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: repeat(10, 80px);
  grid-gap: 2px;
  background-color: #909399;
}

.course-item {
  position: relative;
  padding: 5px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  box-sizing: border-box;
  border: 2px solid transparent;
  transition: all 0.2s;
  background-color: #ffffff;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.course-title {
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 3px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.course-detail {
  font-size: 12px;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

// 不同类型课程的样式
.course-type-1 {
  background-color: rgba(43, 101, 236, 0.85);
  color: white;
}

.course-type-2 {
  background-color: rgba(54, 211, 153, 0.85);
  color: white;
}

.course-type-3 {
  background-color: rgba(156, 163, 175, 0.85);
  color: white;
}

.course-type-4 {
  background-color: rgba(245, 108, 108, 0.85);
  color: white;
}

// 接口已排课数据样式（差异化）
.course-type-5 {
  background-color: rgba(29, 78, 216, 0.9);
  color: white;
  border: 2px solid #1e40af;
  box-shadow: 0 2px 8px rgba(29, 78, 216, 0.2);
}

.course-type-5:hover {
  background-color: rgba(29, 78, 216, 1);
  box-shadow: 0 4px 12px rgba(29, 78, 216, 0.3);
}

// 分隔线样式
::v-deep .el-divider--horizontal {
  margin: 10px 0;
}

// 按钮样式
::v-deep .el-button--success {
  &:hover {
    background-color: #4CAF50;
    border-color: #4CAF50;
  }
}
</style>